<?php

class Router extends Base
{
    protected $currentUrl='', $controllerName='Index', $actionName='index', $route='', $requestParams=array();

    public function __construct()
    {
        $this->parseRequest();
        Sys::app()->request=new Request($this->route, $this->currentUrl, $this->controllerName, $this->actionName, $this->requestParams);
    }

    public function run()
    {
        if(!Sys::app()->controller){
            Sys::app()->error='Неправильный адрес ссылки. Не удалось найти контроллер';
            Request::redirect(404);
        }
        if(!Sys::app()->controller->action){
            Sys::app()->error='Неправильный адрес ссылки. Не удалось найти действие '.$this->actionName.' контроллера '.$this->controllerName;
            Request::redirect(404);
        }else
            Sys::app()->controller->run();
    }

    protected function parseRequest()
    {
        $request=str_replace('/index','',$_SERVER['REQUEST_URI']);
        $request=str_replace('///','/',$request);
        $request=str_replace('//','/',$request);
        $request=BASEURL.self::parseString($request);
        $this->currentUrl=$request;

        $parsedUrl=parse_url($request);
        $request=isset($parsedUrl['path']) ? self::parseString($parsedUrl['path']) : '';
        $actionName=$this->actionName;

        $controllerPath=$controllerPath=CONTROLLERS.$this->controllerName;
        $arrayRequest=array();
        if(strpos($request,'/')){
            $arrayRequest=explode('/',$request);
            if(isset($arrayRequest[0])){
                $name=$arrayRequest[0];
                if($path=$this->searchFile($name,CONTROLLERS)){
                    $controllerPath=$path;
                    $this->controllerName=ucfirst($name);
                    $this->route.=lcfirst($name);
                    unset($arrayRequest[0]);
                }
            }
        }elseif(strlen($request)>1){
            if($path=$this->searchFile($request,CONTROLLERS)){
                $controllerPath=$path;
                $this->controllerName=ucfirst($request);
                $this->route.=lcfirst($request);
            }
        }
        if($arrayRequest){
            $num=isset($arrayRequest[0]) ? 0 : (isset($arrayRequest[1]) ? 1 : false);
            if($num!==false) $actionName=$arrayRequest[$num];
        }

        if($controller=Loader::loadClass($controllerPath)){
            if(method_exists($controller,$actionName)) $this->actionName=$actionName;
            else $actionName=$this->actionName;
            if(method_exists($controller,$actionName)) $this->actionName=$actionName;
            else{
                Sys::app()->error='В контроллере '.$this->controllerName.' нет метода '.$actionName;
                Request::redirect(404);
            }
        }else{
            Sys::app()->error='Нет такого конроллера '.$this->controllerName.'. Путь для поиска: '.$controllerPath;
            Request::redirect(404);
        }

        if(in_array($this->actionName,$arrayRequest)) array_shift($arrayRequest);

        $arrayRequest=array_filter($arrayRequest);
        if($arrayRequest){
            while($name=array_shift($arrayRequest)){
                if($value=array_shift($arrayRequest)) $this->requestParams[$name]=$value;
            }
        }

        $this->route=lcfirst($this->controllerName).'/'.$this->actionName;

        $controller->action=$this->actionName;
        $controller->route=$this->route;
        $controller->params=$this->requestParams;

        Sys::app()->controller=$controller;
    }
}